import { defineStore } from 'pinia'
import { ref } from 'vue'

/**
 * 用户认证状态枚举
 * - unauthenticated: 未认证
 * - authenticating: 认证中
 * - authenticated: 已认证
 * - error: 认证错误
 */
const AUTH_STATES = {
  UNAUTHENTICATED: 'unauthenticated',
  AUTHENTICATING: 'authenticating',
  AUTHENTICATED: 'authenticated',
  ERROR: 'error'
}

/**
 * 用户存储仓库
 * 负责管理全局用户状态、认证信息及用户相关操作
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null as UserInfo | null,       // 用户信息
	userId:,
	username:,
    authState: AUTH_STATES.UNAUTHENTICATED, // 认证状态
    error: null as string | null,           // 错误信息
    token: ''                               // 认证令牌
  }),

  actions: {
    /**
     * 初始化用户状态
     * 从本地存储加载用户信息
     */
    initialize() {
      try {
        this.authState = AUTH_STATES.AUTHENTICATING
        
        const userStr = uni.getStorageSync('user')
        const token = uni.getStorageSync('token')
        
        if (userStr && token) {
          this.userInfo = JSON.parse(userStr)
          this.token = token
          this.authState = AUTH_STATES.AUTHENTICATED
        } else {
          this.clearUserInfo()
        }
      } catch (err) {
        console.error('初始化用户信息失败:', err)
        this.authState = AUTH_STATES.ERROR
        this.error = '初始化用户信息失败'
      }
    },

    /**
     * 设置用户信息（登录时使用）
     * @param {UserInfo} userInfo - 用户信息
     * @param {string} token - 认证令牌
     */
    setUserInfo(userInfo: UserInfo, token: string) {
      try {
        this.authState = AUTH_STATES.AUTHENTICATING
        
        this.userInfo = userInfo
        this.token = token
        
        uni.setStorageSync('user', JSON.stringify(userInfo))
        uni.setStorageSync('token', token)
        
        this.authState = AUTH_STATES.AUTHENTICATED
        this.error = null
      } catch (err) {
        console.error('保存用户信息失败:', err)
        this.authState = AUTH_STATES.ERROR
        this.error = '保存用户信息失败'
      }
    },

    /**
     * 清理用户信息（退出时使用）
     */
    clearUserInfo() {
      this.userInfo = null
      this.token = ''
      this.authState = AUTH_STATES.UNAUTHENTICATED
      this.error = null
      
      uni.removeStorageSync('user')
      uni.removeStorageSync('token')
    },

    /**
     * 更新用户信息（部分更新）
     * @param {Partial<UserInfo>} payload - 要更新的用户信息字段
     */
    updateUserInfo(payload: Partial<UserInfo>) {
      if (!this.userInfo) return
      
      this.userInfo = { ...this.userInfo, ...payload }
      uni.setStorageSync('user', JSON.stringify(this.userInfo))
    },

    /**
     * 检查用户是否已认证
     */
    checkAuth(): boolean {
      return this.authState === AUTH_STATES.AUTHENTICATED && !!this.userInfo
    }
  },

  getters: {
    /**
     * 获取当前用户ID
     */
    userId: (state) => state.userInfo?.userid || '',

    /**
     * 获取当前用户昵称
     */
    nickname: (state) => state.userInfo?.nickname || '',

    /**
     * 获取当前用户头像
     */
    avatar: (state) => state.userInfo?.avatar || '',

    /**
     * 检查是否是房主
     * @param {string} roomId - 房间ID
     */
    isRoomOwner: (state) => (roomId: string) => {
      return state.userInfo?.ownedRooms?.includes(roomId) || false
    },

    /**
     * 检查是否在指定房间中
     * @param {string} roomId - 房间ID
     */
    isInRoom: (state) => (roomId: string) => {
      return state.userInfo?.joinedRooms?.includes(roomId) || false
    }
  },
  
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user-store',
        storage: {
          getItem(key) {
            return uni.getStorageSync(key)
          },
          setItem(key, value) {
            uni.setStorageSync(key, value)
          },
          removeItem(key) {
            uni.removeStorageSync(key)
          }
        }
      }
    ]
  }
})